package com.kmxd.ams.init;

import com.google.common.collect.Lists;
import com.kmxd.ams.client.archive.IArchiveFieldSvc;
import com.kmxd.ams.client.archive.IArchiveTypeSvc;
import com.kmxd.ams.client.archive.dto.ArchiveFieldAddDTO;
import com.kmxd.ams.infra.archive.entity.ArchiveType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * v6:添加文件编号前缀、文件编号序号字段（f表添加字段，元数据表添加字段信息）
 *
 * @author zuolg
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class InitUpgradeV6 {
    private final IArchiveFieldSvc archiveFieldSvc;
    private final IArchiveTypeSvc archiveTypeSvc;


    /**
     * v6:添加文件编号前缀、文件编号序号字段（f表添加字段，元数据表添加字段信息）
     */
    public void initDocNumberField() {
        List<ArchiveType> archTypes = archiveTypeSvc.list();
        System.out.println("===============开始添加文件编号前缀、序号字段");

        archTypes.forEach(
                item -> {
                    try {
                        initDocField(item);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.info("添加文件编号字段出现异常！表：" + item.getBoxTableId());
                    }
                });
        System.out.println("===============结束添加文件编号前缀、序号字段");

    }

    /**
     * 添加文件表字段及元数据
     */
    private void initDocField(ArchiveType archiveType) {
        System.out.println("开始添加文件编号前缀、序号字段，门类：" + archiveType.getName() + "表：" + archiveType.getDocTableId());

        List<FieldBO> fields = Lists.newArrayList();
        // system共有
        fields.add(new FieldBO("doc_number_prefix", "文件编号前缀", "varchar", 32));
        fields.add(new FieldBO("doc_number_sequence", "文件编号序号", "bigint", 20));

        fields.forEach(
                item -> {
                    ArchiveFieldAddDTO archiveField = new ArchiveFieldAddDTO();
                    archiveField.setArchTypeId(archiveType.getId());
                    archiveField.setTableId(archiveType.getDocTableId());
                    archiveField.setDbFieldKey(item.getKey());
                    archiveField.setDbFieldName(item.getName());
                    archiveField.setDbType(item.getType());
                    archiveField.setDbLength(item.getLen());
                    archiveField.setXmlAlias(item.getKey());
                    archiveField.setSort(888);
                    archiveField.setSortList(888);
                    archiveField.setAttrExtends(false);
                    archiveField.setAttrSummary(false);

                    archiveFieldSvc.add(archiveField);
                });
        System.out.println("添加文件编号前缀、序号字段完成，门类：" + archiveType.getName() + "表：" + archiveType.getDocTableId());

    }

}
